<!--
  -    Copyright (c) 2018-2025, hycloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: hycloud
  -->
<template>
    <div class="execution">
        <el-radio-group v-model="tabPosition" @change="changePosition" style="float: right;margin: 0 20px 10px 0">
            <el-radio-button label="all">全部({{total}})</el-radio-button>
            <el-radio-button label="1">已盘({{done}})</el-radio-button>
            <el-radio-button label="0">未盘({{undone}})</el-radio-button>
            <el-radio-button label="2">盘盈({{surplus}})</el-radio-button>
            <el-radio-button label="3">盘亏({{deficient}})</el-radio-button>
        </el-radio-group>
        <basic-container>
            <avue-crud ref="crud"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @size-change="sizeChange"
                       @current-change="currentChange">
                       <template
                                slot="categoryId"
                                slot-scope="scope">
                                {{ getFlName(scope.row.categoryId) }}
                            </template>
                        <template slot="menuLeft">
                            <el-button
                            icon="el-icon-circle-plus"
                            size="small"
                            type="primary"
                            v-loading.fullscreen.lock="loading1"
                            @click="openform">添加盘盈</el-button>
                            <el-button 
                            size="small"
                            type="primary"
                            v-loading.fullscreen.lock="loading"
                            @click="submit">提交盘点结果</el-button>
                        </template>
                        <template slot="menu" slot-scope="scope">
                            <el-button type="text"
                            size="small"
                            @click="editform(scope)">修改</el-button>
                            <el-button type="text"
                            v-if="scope.row.status == '2'"
                            size="small"
                            @click="remove(scope)">删除盘盈</el-button>
                        </template>
            </avue-crud>
        </basic-container>
        <el-dialog
            title="添加盘盈"
            class="asset-dialog"
            v-if="dialogVisible"
            :visible.sync="dialogVisible"
            @close="closeDialog1"
            append-to-body
            :close-on-click-modal="false"
            top="5vh"
            width="90%">
            <div class="content">
                <el-form :model="assetForm" ref="assetForm" :rules="rules" label-width="100px">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="资产类别" prop="categoryId">
                                <el-cascader
                                :options="treeData"
                                v-model="assetForm.categoryId"
                                :props="cProps"
                                clearable></el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="资产编码" prop="no">
                                <el-input v-model="assetForm.no" :maxlength="32"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="资产名称" prop="name">
                                <el-input v-model="assetForm.name" :maxlength="128"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="规格型号">
                                <el-input v-model="assetForm.spec" :maxlength="64"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="计量单位">
                                <el-input v-model="assetForm.unit" :maxlength="12"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="使用人">
                                <el-input  placeholder="请选择使用人" v-model="useId_str"  @focus="choseMember('useId')">
                                    <el-button slot="append" @click="choseMember('useId')">选择</el-button>
                                </el-input>
                                <!-- <el-input v-model="assetForm.useId"></el-input> -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="使用部门">
                                <el-input v-model="assetForm.useDeptName" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="区域" prop="areaId">
                                <el-cascader
                                :options="treeData1"
                                v-model="assetForm.areaId"
                                :props="aProps"
                                clearable></el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="存放地点">
                                <el-input v-model="assetForm.address" :maxlength="64"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="16">
                            <el-form-item label="备注">
                                <el-input v-model="assetForm.remark" type="textarea"  :maxlength="256" :rows="5"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="8">
                            <el-form-item label="照片">
                                <el-upload
                                    :headers="headers"
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess"
                                    class="avatar-uploader"
                                    action="/act/file/upload"
                                    >
                                    <img
                                        v-if="avatarUrl"
                                        id="avatar"
                                        :src="avatarUrl"
                                        class="avatar"
                                    />
                                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                                    </el-upload>
                            </el-form-item>
                        </el-col> -->
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog1">取 消</el-button>
                <el-button type="primary" @click="alarmHandle('assetForm')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :visible.sync="modal4"
            v-if="modal4"
            title="修改"
            width="30%"
            @close="closeDialog2"
            :close-on-click-modal="false"
            append-to-body>
            <el-form :model="assetform1" label-width="120px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="修改后区域" prop="supplier">
                            <el-cascader
                                :options="treeData1"
                                v-model="assetform1.areaId"
                                :props="aProps"
                                clearable></el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="修改后存放地点">
                            <el-input v-model="assetform1.address" :maxlength="64"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="修改后使用人">
                            <el-input  placeholder="请选择使用人" v-model="useId1_str"  @focus="choseMember('useId1')">
                                <el-button slot="append" @click="choseMember('useId1')">选择</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="修改后使用部门">
                            <el-input v-model="assetform1.useDeptName" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog2">取 消</el-button>
                <el-button type="primary" @click="alarmHandle1('assetform1')">确 定</el-button>
            </span>
        </el-dialog>
         <choose-member v-if="showChose" :labelkey="labelkey" :url1="url1" :url2="url2" :title="title1" :columns1="columns1" :columns="columns" :type="type" :flKey="flKey"></choose-member>
    </div>
</template>

<script>
    import {fetchList, deficient, putObj, delObj, surplus} from '@/api/asset/assetinventoryrecord'
    import {submit} from '@/api/asset/assetinventory'
    import { fetchTree, fetchList as fetchList1 } from '@/api/asset/assetcategory'
    import { fetchTree as fetchTree1 } from '@/api/admin/sysarea'
    import store from '@/store'
     import chooseMember from '@/components/chooseMember'
    import eventBus from '@/util/eventBus'
    import {tableOption} from '@/const/crud/asset/assetinventoryrecord'
    import {mapGetters} from 'vuex'

    export default {
        name: 'assetinventoryrecord',
        components: { chooseMember },
        props: ['inventoryId'],
        data() {
            return {
                cProps: {
                    label: 'name',
                    value: 'id',
                    emitPath:false,
                    checkStrictly: true
                },
                aProps: {
                    label: 'name',
                    value: 'id',
                    emitPath:false,
                    checkStrictly: true
                },
                loading: false,
                loading1: false,
                assetform1: {
                    areaId:'',
                    useDeptName:'',
                    address:'',
                    useRealname:'',
                    id:'',
                },
                recordId: '',
                modal4: false,
                useId_str: '',
                useId1_str: '',
                avatarUrl: '',
                dialogVisible: false,
                tabPosition: 'all',
                searchForm: {},
                tableData: [],
                assetForm: {},
                total: 0,
                undone: 0,
                flList: [],
                deficient: 0,
                treeData: [],
                treeData1: [],
                done: 0,
                flKey: '',
                url1: '',
                url2: '',
                type:'',
                columns:[],
                columns1:[],
                title1: '',
                withMember_str: '',
                labelkey: '',
                showChose: false,
                surplus: 0,
                rules: {
                    categoryId: [
                        { required: true, message: '请选择资产类别' }
                    ],
                    no: [
                        { required: true, message: '请输入资产编码', trigger: 'blur' },
                    ],
                    name: [
                        { required: true, message: '请输入资产名称', trigger: 'blur' }
                    ]
                },
                keyNum: 0,
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            headers() {
                return {
                    Authorization: "Bearer " + store.getters.access_token
                }
            },
            permissionList() {
                return {
                    addBtn: false,
                    delBtn: false,
                    editBtn: false
                };
            }
        },
        created() {
            this.init()
            this.eventBusHandle()
        },
        methods: {
            init() {
                fetchList1({current: 1, size:1000}).then(response => {
                    this.flList = response.data.data.records
                })
                fetchTree().then(response => {
                    this.treeData = response.data.data
                })
                fetchTree1().then(response => {
                    this.treeData1 = response.data.data
                })
            },
            editform(scope){
                this.useId1_str = ''
                this.recordId = scope.row.recordId
                if (scope.row.updateAreaId) {
                    this.assetform1.areaId = scope.row.updateAreaId
                }
                if (scope.row.updateUseDeptName) {
                    this.assetform1.useDeptName = scope.row.updateUseDeptName
                }
                if (scope.row.updateUseRealname) {
                    this.assetform1.useRealname = scope.row.updateUseRealname
                    this.useId1_str = scope.row.updateUseRealname
                    this.assetform1.useId = scope.row.updateUseId
                }
                if (scope.row.updateAddress) {
                    this.assetform1.address = scope.row.updateAddress
                }
                this.modal4 = true
            },
            submit() {
                let _this= this
                this.$alert('盘盈资产自动入库，已盘资产修改内容自动更新资产信息', '提交盘点结果', {
                    confirmButtonText: '确定',
                    callback: action => {
                        if (action === 'cancel') {
                        } else {
                             _this.loading = true
                            submit(this.inventoryId).then(response => {
                                this.loading = false
                                this.$message.success('提交成功')
                                this.getList(this.page)
                            }).catch(() => {
                                this.loading = false
                            });
                        }
                    }
                });
            },
            handleAvatarSuccess(res, file, fileList) {
                this.avatarUrl = URL.createObjectURL(file.raw)
                this.assetForm.cover = res.data.url
                this.keyNum += 1
            },
            openform() {
                this.dialogVisible = true
            },
            alarmHandle1(formName) {
                const _this = this
                this.assetform1.id = this.recordId
                putObj(this.assetform1).then(data => {
                    this.$message.success('修改成功')
                    this.closeDialog2()
                    this.getList(this.page)
                })
            },
            eventBusHandle () {
                let _this = this
                eventBus.$on('getMember', function (data) {
                    if (data.useId_choose_member) {
                        _this.assetForm.useId = data.useId[0].userId
                        _this.assetForm.useRealname = data.useId[0].realname
                        _this.assetForm.useDeptName = data.useId[0].deptName
                        _this.assetForm.useDeptId = data.useId[0].deptId
                        _this.useId_str = data.useId_choose_member
                    } else if (data.useId1_choose_member) {
                        _this.assetform1.useId = data.useId1[0].userId
                        _this.assetform1.useRealname = data.useId1[0].realname
                        _this.assetform1.useDeptName = data.useId1[0].deptName
                        _this.assetform1.useDeptId = data.useId1[0].deptId
                        _this.useId1_str = data.useId1_choose_member
                    }
                })
            },
            choseMember (id) {
                this.type = "radio"
                this.labelkey = id + '_choose_member'
                this.url1 = '/admin/dept/tree'
                this.url2 = '/admin/user/page/simple'
                this.title1 = '组织机构'
                this.flKey = 'deptId'
                this.columns = [
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '姓名',
                    key: 'realname',
                    dataIndex: 'realname',
                },
                {
                    title: '所属部门',
                    dataIndex: 'deptId',
                    key:'deptId',
                    scopedSlots: { customRender: 'deptId' },
                },
                {
                    title: '岗位',
                    dataIndex: 'post',
                    key: 'post',
                    scopedSlots: { customRender: 'post' }
                }
                ]
                this.columns1 = [
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username' 
                },
                {
                    title: '操作',
                    key: 'action',
                    scopedSlots: { customRender: 'action' },
                },
                ]
                this.showChose = true
            },
            closeDialog1() {
                this.dialogVisible = false
                this.assetForm = {}
            },
            closeDialog1() {
                this.dialogVisible = false
                this.assetForm = {}
            },
            closeDialog2() {
                this.modal4 = false
                this.assetform1 = {
                    areaId:'',
                    useDeptName:'',
                    address:'',
                    useRealname:'',
                    id:'',
                }
            },
            changePosition(val) {
                if(val != 'all') {
                    this.getList(this.page, {status: val})
                } else {
                    this.getList(this.page)
                }
            },
            alarmHandle(formName) {
                const _this = this
                this.assetForm.inventoryId = this.inventoryId
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                         _this.loading = true
                        surplus(_this.assetForm).then(response => {
                            _this.loading = false
                            _this.$message.success('添加成功')
                            _this.closeDialog1()
                            _this.getList(_this.page)
                        })
                    }
                })
            },
            remove(scope) {
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(scope.row.recordId)
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            getList(page, params) {
                this.tableLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    inventoryId: this.inventoryId
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.undone = response.data.data.undone
                    this.done = response.data.data.done
                    this.deficient = response.data.data.deficient
                    this.surplus = response.data.data.surplus
                    this.total = response.data.data.all
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            getFlName(id) {
                let list =  this.flList.filter(item => {
                    return item.categoryId === id
                })
                return list.length > 0 ? list[0].name : ''
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>
<style scoped lang="scss">
.el-cascader, .el-select, .el-input-number, .el-date-editor {
    width: 100%;
}
.asset-dialog{
    /deep/.el-dialog__body{
        height: 80vh;
        overflow: auto;
    }
    
    /deep/.avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    /deep/.avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }

    /deep/.avatar-uploader-icon {
        font-size: 28px !important;
        color: #8c939d !important;
        width: 178px !important;
        height: 178px !important;
        line-height: 178px !important;
        text-align: center !important;
    }

    /deep/.avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
}
</style>
